package com.yunhe.commens.dao.impl;

import com.yunhe.commens.dao.BaseDao;
import com.yunhe.commens.dto.Pagedao;
import com.yunhe.commens.util.JdbcHelp;
import com.yunhe.sms.entity.activity.Vote;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author LeiPeifeng
 * @version V1.0
 * @date 2017/10/17 0017 13:27
 * @Description: 实现接口BaseDao
 */
public class BaseDaoImpl<T> implements BaseDao<T>{
    private Class<T> clazz;//当前dao对应的实体的class对象

    /**
     * 构造器 获取泛型的实际类型
     */
    @SuppressWarnings ( "unchecked" )
    public BaseDaoImpl(){
        @SuppressWarnings ( "rawtypes" )
        Class clazz = getClass ();
        while (clazz!=Object.class){
            Type superclass = clazz.getGenericSuperclass ();//当前对象的直接超类的 Type
            if (superclass instanceof ParameterizedType){
                ParameterizedType superclass1 = (ParameterizedType) superclass;
                Type[] Type = superclass1.getActualTypeArguments ();//返回表示此类型实际类型参数的 Type 对象的数组
                if (Type[0] instanceof Class){
                    this.clazz=(Class<T>)Type[0];
                    break;
                }
            }
            clazz=clazz.getSuperclass ();
        }
    }


    protected T quaryOne(String sql, Object... params) {
        QueryRunner queryRunner = new QueryRunner ( JdbcHelp.getDataSource () );
        T query=null;
        try {
             query = queryRunner.query ( sql, new BeanHandler<T> ( clazz ),params );
        } catch (SQLException e) {
            e.printStackTrace ();
        }
        return query;
    }


    protected List<T> quaryList(String sql, Object... params) {
        ArrayList list = new ArrayList ();
        if (null!=list){
            for (int i=0;i<params.length;i++){
                if (null != params[i]){
                    list.add ( params[i] );
                }
            }
        }
        QueryRunner queryRunner = new QueryRunner ( JdbcHelp.getDataSource () );
        List<T> query=null;
        try {
            query = queryRunner.query ( sql, new BeanListHandler<T> ( clazz ),list.toArray () );
        } catch (SQLException e) {
            e.printStackTrace ();
        }
        return query;
    }

    protected Pagedao<T> quaryPage(String listsql, String countsql,int offset,int size, Object... params) {
//        过滤无效参数
        List list = new ArrayList ();
        if (null!=list){
            for (int i=0;i<params.length;i++){
                if (null != params[i]){
                    list.add ( params[i] );
                }
            }
        }

        Pagedao<T> pagedao =new Pagedao<> ();
        QueryRunner queryRunner = new QueryRunner ( JdbcHelp.getDataSource () );
        List<T> query=null;
        Long count=0l;
        try {
             count = queryRunner.query ( countsql, new ScalarHandler<Long> ( ));//总数
             if (count>0){
                 list.add ( offset );
                 list.add ( size );
                 listsql+=" limit ?,?";
                 pagedao.setPage ( offset/size+1 );
                 pagedao.setSize ( size );
                 query = queryRunner.query ( listsql, new BeanListHandler<T> ( clazz ),list.toArray () );//本业数据
             }
        } catch (SQLException e) {
            e.printStackTrace ();
        }

        pagedao.setTotal ( count.intValue () );
        pagedao.setRows ( query );
        return pagedao;
    }


    /**
     * 返回受影响行数
     * @param sql
     * @param params
     * @return
     */
    protected int cut(String sql, Object... params) {
        QueryRunner queryRunner = new QueryRunner ( JdbcHelp.getDataSource () );
        int i=0;
        try {
           i = queryRunner.update ( sql, params );
        } catch (SQLException e) {
            e.printStackTrace ();
            throw new RuntimeException("cud执行失败");
        }
        return i;
    }

    /**
     * 保存时，返回id
     * @param sql
     * @param params
     * @return
     */
    protected Long insert(String sql, Object... params) {
        Long key;
        QueryRunner qr = new QueryRunner(JdbcHelp.getDataSource());
        try {
            key = qr.insert(sql, new ScalarHandler<Long>(), params);
        } catch (SQLException e) {

            throw new RuntimeException(e);
        }
        return key;
    }
}
